/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.activity.impl;

import org.sabayframework.activity.ActivityContext;
import org.sabayframework.channel.Lock;

/**
 * Activity outputs all elements that were passed in the constructor. 
 * @author Alex Antonau
 * */
public class Emit<O> extends OutputActivity<O> {

	private O[] elems;
	private int count;
	
	/**
	 * Default constructor for deserialization.
	 * */
	protected Emit() {
		super();
	}

	/**
	 * Constructor accepts elements to be passed to the output channel 
	 * @param elems
	 * @SafeVarargs
	 */
	public Emit(O... elems) {
		this(true, elems);
	}

	/**
	 * Constructor accepts elements to be passed to the output channel 
	 * @param closeOutput true if output should be closed after activity completion, 
	 * false - otherwise
	 * @param elems
	 * @SafeVarargs
	 */
	public Emit(Boolean closeOutput, O... elems) {
		super(closeOutput);
		this.elems = elems;
		
	}

	protected void setElems(O[] elems) {
		this.elems = elems;
	}

	@Override
	public boolean isReady(ActivityContext<O, O> ctx) throws Exception {
		if(count >= elems.length) return false;
		return super.isReady(ctx);
	}

	@Override
	public void output(ActivityContext<O, O> ctx, Lock<O> outputLock) {
		outputLock.set(0, elems[count++]);
	}

	@Override
	public boolean isDone(ActivityContext<O, O> ctx) throws Exception {
		if(count >= elems.length) return true;
		return super.isDone(ctx);
	}

}
